#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# @Time    : 2023/4/9 17:02
# @Author  : WJQ
# @Site    : 
# @File    : driver_wx.py
# @Software: PyCharm
import os
import time, json
import traceback

from urllib.parse import quote
from selenium.webdriver.support.ui import WebDriverWait
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support import expected_conditions as EC

import conf
from browser.driver import DriverHandler
from browser.page import PageHandler
from crawler.modules_native.instrument import back_previous_page
from utils.common import CrawlerLogger, open_app, kill_app

from utils.get_app_json import copy_Pkg_Down_zfb, unpack_and_copy_json_zfb


class DriverHandlerZfb(DriverHandler):
    def __init__(self, applets_name):
        super().__init__(applets_name, 86, 4724)
        self.appid_dict = {
            '国务院客户端': '2021001123608001'
        }

    @classmethod
    def create(cls, applets_name):
        self = DriverHandlerZfb(applets_name)
        return self

    def get_alipay_url(self) -> str:
        # e.g. https://2021001123608001.hybrid.alipay-eco.com/index.html#pages/housing-fund/housing-fund?__appxPageId=3
        # 确保已经附加到应用
        self.attach_to_app('com.eg.android.AlipayGphone', 'alipay')
        # 从 Frida 脚本获取路径
        url = self.script.exports.get_url()  # 这里应该返回一个字符串
        return url
    
    def get_alipay_appid(self) -> str:
        # e.g. 2021001123608001
        # 确保已经附加到应用
        self.attach_to_app('com.eg.android.AlipayGphone', 'alipay')
        # 从 Frida 脚本获取路径
        appid = self.script.exports.get_appid()  # 这里应该返回一个字符串
        return appid

    def get_url( self ) -> (str, str):
        # 获取当前页面的 path
        try:
            url = self.get_alipay_url()
            path = url.split("#")[1].split("?")[0]
            query = url.split("?")[1] if len(url.split("?")) > 1 else ""
            return path, query
        except Exception as e :
            CrawlerLogger.debug(f"Error getting driver title: {e}")
            return "pages/index/index", ""

    def get_all_pages( self, file_path ):
        with open(file_path, 'r', encoding='utf-8') as f :
            json_data = json.load(f)
        launch_params_keys = list(json_data.get('launchParams', {}).keys())
        return launch_params_keys

    def enter_mini_program(self, applets_name, flag=True):
        '''
        进入对应小程序
        :param applets_name:
        :return:
        '''
        self.detach_from_app()
        kill_app("com.eg.android.AlipayGphone", conf.CLIENT_SIDE_CONF.DEVICE_ID)
        open_app("com.eg.android.AlipayGphone", "com.eg.android.AlipayGphone.AlipayLogin", conf.CLIENT_SIDE_CONF.DEVICE_ID)
        self.attach_to_app('支付宝', 'alipay')
        time.sleep(2)
        # 等待首页出现
        try:
            WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((AppiumBy.XPATH, "//*[@text='我的']"))
            )
            # 进入小程序
            CrawlerLogger.info(f"[+] 进入小程序...")

            PageHandler.safe_click_element(self.driver, AppiumBy.ID,
                                           "com.alipay.android.phone.openplatform:id/more_app_icon")
            WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((AppiumBy.XPATH, "//*[@text='我的应用']"))
            )
            PageHandler.safe_click_element(self.driver, AppiumBy.ID,
                                                   "com.alipay.mobile.antui:id/search_input_box")
            WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((AppiumBy.XPATH, "//*[@text='搜索您感兴趣的应用']"))
            )
        except Exception as e:
            pass
        input = PageHandler.safe_find_element(self.driver, AppiumBy.ID, "com.alipay.mobile.antui:id/search_input_box")
        input.send_keys(applets_name)
        time.sleep(2)
        PageHandler.safe_click_element(self.driver, AppiumBy.XPATH,
                                       f"//android.widget.TextView[contains(@text, '{applets_name}') and not(@text = '{applets_name} - 服务')]")
        time.sleep(4)

        if self.get_alipay_appid():
            self.appid = self.get_alipay_appid()
            CrawlerLogger.info(f"[*] 进入小程序成功...")
        else:
            CrawlerLogger.error(f"[-] 进入小程序失败...")
            self.enter_mini_program(applets_name)


    def get_app_json( self , applets_name):
        try:
            self.appid = self.get_alipay_appid()
            with open(f'./experiment/zfb_files/large_scale/applet_info.json', 'r', encoding='utf-8') as f :
                applet_info = json.load(f)
            applet_info[self.applets_name] = self.appid
            with open(f'./experiment/zfb_files/large_scale/applet_info.json', 'w', encoding='utf-8') as f :
                json.dump(applet_info, f, ensure_ascii=False, indent=4)
            if not os.path.exists('./experiment/zfb_files/pkgs_handle/' + self.applets_name) :
                os.mkdir('./experiment/zfb_files/pkgs_handle/' + self.applets_name)
            copy_Pkg_Down_zfb(self.appid, './experiment/zfb_files/pkgs_handle/' + self.applets_name,
                        conf.CLIENT_SIDE_CONF.DEVICE_ID)
            unpack_and_copy_json_zfb(applets_name, f'./experiment/zfb_files/pkgs_handle/{self.applets_name}/{self.appid}', './experiment/app_json/zfb')
        except Exception as e :
            CrawlerLogger.error(f"[-] {traceback.format_exc()}")
            CrawlerLogger.debug(f"[-] {self.applets_name}未找到AppID")
            exit()

    def go_to_target_url ( self, target_path: str, query: str = "" ):
        # ('pages/base/base', '__appxPageId=4&url=https://app.www.gov.cn/govdata/gov/202312/28/510658/article.html')
        self.attach_to_app('com.eg.android.AlipayGphone', 'alipay')
        # 使用 Frida 脚本跳转到指定页面
        if query:
            query = quote(query, safe='')
            url = f"/{target_path}?{query}"
        else:
            url = f"/{target_path}"
        self.script.exports.jump(self.appid, url)
        time.sleep(2)